#加载数据集
import pandas as pd
names = ['age','height','weight','gender']
dataset = pd.read_csv('item6/gender-data-y.txt',delimiter=',',names=names)
print(dataset)
#数据预处理
from sklearn import preprocessing
#将身高和体重转换为浮点型
dataset['height'] = dataset['height'].astype(float)
dataset['weight'] = dataset['weight'].astype(float)
#将性别进行数值化处理
le = preprocessing.LabelEncoder()#标签编码
dataset['label'] = le.fit_transform(dataset['gender'])
print(dataset)
#数据集可视化
import matplotlib.pyplot as plt
data = dataset.iloc[range(0,100),range(1,3)].values#提取身高和体重数据
target = dataset.iloc[range(0,100),range(4,5)].values.reshape(1,100)[0]#提取标签值
#绘制散点图
plt.scatter(data[target==0,0],data[target==0,1],s=60,c='r',marker='o')
plt.scatter(data[target==1,0],data[target==1,1],s=60,c='g',marker='^')

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.xlabel('身高CM')
plt.ylabel('体重KG')
plt.show()
#寻找最佳深度值
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

#分割数据集
x,y= data, target
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=30,random_state=0)
#定义备选的深度数组、误差率数组
depths = np.arange(1,15)
errs =[]
#开始遍历
for i in depths:
    model = DecisionTreeClassifier(max_depth=i,criterion='entropy')
    model.fit(x_train,y_train)
    pred = model.predict(x_test)
    ac = accuracy_score(y_test,pred)
    err = 1 - ac
    errs.append(ac)
#绘制深度与误差率的图形
plt.plot(depths,errs,'ro-')
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.xlabel('深度')
plt.ylabel('误差率')
plt.show()
#开始使用5或6作为深度来训练模型并进行计算
from sklearn.metrics import classification_report

model = DecisionTreeClassifier(criterion='entropy',max_depth=5)
model.fit(x_train,y_train)
pred = model.predict(x_test)
re = classification_report(y_test,pred)
print(re)
#显示分类结果，并进行数据可视化
from matplotlib.colors import ListedColormap
#绘制分类界面
N,M =500,500
t1 =np.linspace(140,195,N)
t2 =np.linspace(30,90,M)
x1,x2 =np.meshgrid(t1,t2)
x_new = np.stack((x1.flat,x2.flat),axis=1)
y_predict = model.predict(x_new)
y_hat = y_predict.reshape(x1.shape)
iris_cmap = ListedColormap(["#ACC6C0","#FF8080"])
plt.pcolormesh(x1,x2,y_hat,cmap=iris_cmap)

#绘制两个类别的样本数据点
plt.scatter(x[y==0,0],x[y==0,1],s=60,c='r',marker='o')
plt.scatter(x[y==1,0],x[y==1,1],s=60,c='g',marker='^')
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.xlabel('身高CM')
plt.ylabel('体重KG')
plt.show()

